package framework.http.net;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import framework.http.bean.Image;
import framework.manage.ManageApp;
import framework.utils.LogUtils;
import framework.utils.StringUtils;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

public class ImageLoader {
	private byte[] lock = new byte[0];
	private HashMap<String, SoftReference<Drawable>> imageCache;
	private BlockingQueue queue;
	private ThreadPoolExecutor executor;

	public ImageLoader() {
		imageCache = new HashMap<String, SoftReference<Drawable>>();
		queue = new LinkedBlockingQueue();
		executor = new ThreadPoolExecutor(5, 8, 180, TimeUnit.SECONDS, queue);
	}

	public void clear() {
		Set<String> keySet = imageCache.keySet();
		for (String key : keySet) {
			SoftReference<Drawable> softReference = imageCache.remove(key);
			Drawable drawable = softReference.get();
			drawable = null;
			softReference = null;
		}
		imageCache = null;
		queue = null;
		executor = null;
	}

	public Drawable loadDrawable(final Context context,final Image image, final ImageCallback imageCallback) {
		final String imageUrl = image.getUrl();

		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Drawable> softReference = imageCache.get(imageUrl);
			if (softReference != null) {
				Drawable drawable = softReference.get();
				if (drawable != null) {
					// LogUtils.log("内存缓存的图片", getClass());
					return drawable;
				} else {
					softReference = null;
					imageCache.remove(imageUrl);
				}
			} else {
				imageCache.remove(imageUrl);
			}
		}

		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Drawable) message.obj, imageUrl);

			}
		};

		executor.execute(new Runnable() {
			public void run() {
				Drawable drawable = loadImageFromUrl(context,image);
				if (drawable != null) {
					imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
				}
				Message message = handler.obtainMessage(0, drawable);
				handler.sendMessage(message);
			}
		});

		return null;
	}

	private Drawable loadImageFromUrl(Context context,final Image image) {
		synchronized (lock) {
			Drawable drawable = null;
			String imageUrl = image.getUrl();
			if (TextUtils.isEmpty(imageUrl)) {
				return null;
			}
			String fileName = fileName = image.getName();
			String imagePath = image.getPath();

			File fileDir = new File(ManageApp.getImageFileDir(context) + imagePath);
//			File fileDir = new File(PhoneParameters.imageFileDir + imagePath);
			if (!fileDir.exists()) {
				fileDir.mkdirs();
			}

			File file = new File(fileDir, fileName);// 保存文件

			if (!file.exists() && !file.isDirectory()) {
				File tempFile = new File(fileDir, fileName + ".tmp");
				FileOutputStream fos = null;
				InputStream is = null;
				HttpURLConnection conn = null;
				try {
					fos = new FileOutputStream(tempFile);
					URL url = new URL(imageUrl);
					conn = (HttpURLConnection) url.openConnection();
					conn.setConnectTimeout(600000);
					conn.setRequestProperty("Connection", "keep-alive");
					conn.setRequestProperty("Referer", image.getHost());

					is = new BufferedInputStream(conn.getInputStream());
					int responseCode = conn.getResponseCode();
					if (responseCode != 200) {
						return null;
					}

					byte[] buf = new byte[500];
					int len = is.read(buf);
					while (len != -1) {
						fos.write(buf, 0, len);
						len = is.read(buf);
					}
					// LogUtils.log("网路的图片", getClass());
					drawable = BitmapDrawable.createFromPath(tempFile.toString());
					boolean renameTo = tempFile.renameTo(file);
				} catch (IOException e) {
					exception(e);
					return null;
				} catch (OutOfMemoryError e) {
					LogUtils.exception(e);
					return null;
				} finally {
					if (is != null) {
						try {
							is.close();
						} catch (IOException e) {
							exception(e);
						}
					}
					if (fos != null) {
						try {
							fos.close();
						} catch (IOException e) {
							exception(e);
						}
					}
					if (conn != null) {
						conn.disconnect();
					}
				}
			} else {
				// LogUtils.log("本地缓存的图片", getClass());
				drawable = BitmapDrawable.createFromPath(file.toString());
			}
			return drawable;
		}
	}

	public interface ImageCallback {
		public void imageLoaded(Drawable loadDrawable, String imageUrl);
	}

	private void exception(Exception e) {
		LogUtils.exception(e);
	}
}
